

<template>
  <p>
    Ask a yes/no question:
    <input v-model="question" :disabled="loading" />
  </p>
  <p>{{ answer }}</p>
</template>
<script>
export default {
  data() {
    return {
      question: '',
      answer: 'Questions usually contain a question mark. ;-)',
      loading: false,
    }
  },
  watch: {
    // whenever question changes, this function will run
    question(newQuestion, oldQuestion) {
      if (newQuestion.includes('?')) {
        this.getAnswer()
      }
    }
  },
  methods: {
    async getAnswer() {
      this.loading = true
      this.answer = 'Thinking...'
      setTimeout(() => {
        try {
            // fetch('https://yesno.wtf/api') 发送一个ajax请求get
            const res = fetch('https://yesno.wtf/api').then(res => this.answer = (res.json()).answer)
            
        } catch (error) {
            this.answer = 'Error! Could not reach the API. ' + error
        } finally {
            this.loading = false
        }
      }, 2000); // 模拟网络请求，2秒后获取答案
    }
  }
}
</script>